﻿using Vboot.Core.Module.Bpm;

namespace Vboot.Extend.Oa;

public class OaFlowTmplService : BaseMainService<OaFlowTmpl>, ITransient
{
    public async Task Insertx(OaFlowTmpl oaFlowTmpl)
    {
        BpmProcTmpl bpmProcTmpl = new BpmProcTmpl();
        bpmProcTmpl.name = oaFlowTmpl.name;
        bpmProcTmpl.crman = oaFlowTmpl.crman;
        bpmProcTmpl.crtim = oaFlowTmpl.crtim;
        bpmProcTmpl.orxml = oaFlowTmpl.prxml;
        bpmProcTmpl.chxml = "<?xml version=\"1.0\" encoding=\"gb2312\"?>"
                            + "\n<process" + bpmProcTmpl.orxml.Split("bpmn2:process")[1]
                                .Replace("bpmn2:", "").Replace("activiti:", "") + "process>";
        bpmProcTmpl.id = YitIdHelper.NextId() + "";
        await repo.Context.Insertable(bpmProcTmpl).ExecuteCommandAsync();
        oaFlowTmpl.protd = bpmProcTmpl.id;
        await InsertAsync(oaFlowTmpl);
    }

    // public async Task Updatex(OaFlowTmpl oaFlowTmpl)
    // {
    //     var bpmProcTmpl = await repo.Context.Queryable<BpmProcTmpl>()
    //         .Where(it => it.id == oaFlowTmpl.protd).FirstAsync();
    //     bpmProcTmpl.orxml = oaFlowTmpl.prxml;
    //     bpmProcTmpl.chxml = "<?xml version=\"1.0\" encoding=\"gb2312\"?>"
    //                         + "\n<process" + bpmProcTmpl.orxml.Split("bpmn2:process")[1]
    //                             .Replace("bpmn2:", "").Replace("activiti:", "") + "process>";
    //     await repo.Context.Updateable(bpmProcTmpl).ExecuteCommandAsync();
    //     await UpdateAsync(oaFlowTmpl);
    // }
    
    public async Task Updatex(OaFlowTmpl oaFlowTmpl)
    {
        var bpmProcTmpl = await repo.Context.Queryable<BpmProcTmpl>()
            .Where(it => it.id == oaFlowTmpl.protd).FirstAsync();
        if (bpmProcTmpl.orxml!=oaFlowTmpl.prxml)
        {
            string newid= YitIdHelper.NextId()+"";
            oaFlowTmpl.protd=newid;
            BpmProcTmpl newBpmProcTmpl=new BpmProcTmpl();
            newBpmProcTmpl.id=newid;
            newBpmProcTmpl.orxml = oaFlowTmpl.prxml;
            string chxml = "<?xml version=\"1.0\" encoding=\"gb2312\"?>"
                           + "\n<process" + newBpmProcTmpl.orxml.Split("bpmn2:process")[1]
                               .Replace("bpmn2:", "")
                               .Replace("activiti:", "") + "process>";
            newBpmProcTmpl.chxml=chxml;
            await repo.Context.Insertable(newBpmProcTmpl).ExecuteCommandAsync();
        }
        await UpdateAsync(oaFlowTmpl);
    }


    public OaFlowTmplService(SqlSugarRepository<OaFlowTmpl> repo)
    {
        this.repo = repo;
    }
}